package com.manatee.multiple.v2.async;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.manatee.multiple.v2.db.DbQuery;
import com.manatee.multiple.v2.test.MyRecordEntity;

/**
 * 
 * @author 6806291@google.com (Gary Lee)
 * @QQ 6806291
 * @date 2012-10-24
 *
 */
public class AsynchronousRunner implements Runnable {

	private static Logger log = LoggerFactory.getLogger(AsynchronousRunner.class);
	private String runnerId;//runner unque id
	private CountDownLatch startCDL;
	private CountDownLatch stopCDL;
	private Class mulRecordType;
	public List<?> dataList;
	
	/**
	 * 
	 * @param runnerId
	 * @param startCDL
	 * @param stopCDL
	 */
	public <T> AsynchronousRunner(String runnerId, CountDownLatch startCDL, CountDownLatch stopCDL, Class<T> mulRecordType){
		this.runnerId = runnerId;
		this.startCDL = startCDL;
		this.stopCDL = stopCDL;
		this.mulRecordType = mulRecordType;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try{
			if(startCDL.await(15, TimeUnit.SECONDS)){
				//start
				
				try {
					dataList = new DbQuery().querySQL(mulRecordType);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				log.info("Runner[{}] complete.", runnerId);
			}else{
				//timeout
				log.warn("startCDL[{}] Timeout.", runnerId);
			}
		}catch(InterruptedException e){
			e.printStackTrace();
		}finally{
			stopCDL.countDown();
		}
	}

}
